#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

typedef pair<int, int> PII;
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };

class Solution {
public:
    int maxAreaOfIsland(vector<vector<int>>& grid) {
        int n = grid.size(), m = grid[0].size();
        vector<vector<int>> st(n, vector<int>(m));
        queue<PII> q;

        int res = 0;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (grid[i][j] == 1 && !st[i][j])
                {
                    q.push({ i,j });
                    st[i][j] = true;
                    int count = 0;
                    while (q.size())
                    {
                        auto t = q.front();
                        count++;
                        q.pop();
                        for (int i = 0; i < 4; i++)
                        {
                            int a = t.first + dx[i];
                            int b = t.second + dy[i];
                            if (a < 0 || a >= n || b < 0 || b >= m)  continue;
                            if (grid[a][b] == 0 || st[a][b])    continue;

                            st[a][b] = true;
                            q.push({ a,b });
                        }
                        res = max(res, count);
                    }
                }
        return res;
    }
};